/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package quiztech3000;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.util.Duration;

/**
 *
 * @author haubuchon
 */

public class quiztechController
        implements Initializable {

    final int NBPLAYERS = 4;
    final int QVALUE = 10;
    final String MEDIAFOLDER = "file:///c:/apps/QuizTech3000";
    private int currentQuestion;
    List<Question> question;
    Map<String, Integer> scores = new HashMap();
    @FXML //  fx:id="scoreLabel1"
    private Text scoreLabel1; // Value injected by FXMLLoader
    @FXML //  fx:id="scoreLabel2"
    private Text scoreLabel2; // Value injected by FXMLLoader
    @FXML //  fx:id="nextQuestionButton"
    private Polygon nextQuestionButton; // Value injected by FXMLLoader
    @FXML //  fx:id="prevQuestionButton"
    private Polygon prevQuestionButton; // Value injected by FXMLLoader
    @FXML //  fx:id="questionArea"
    private Label questionArea; // Value injected by FXMLLoader
    @FXML //  fx:id="actionButton"
    private Button actionButton; // Value injected by FXMLLoader
    @FXML //  fx:id="mediaArea"
    private StackPane mediaArea; // Value injected by FXMLLoader    
    
    private MediaView mediaView;
    private MediaPlayer player;
    private ImageView imageView;
    private Media media;
    private Image image;
    
    
    // Handler for Rectangle[id="scoreButton1"] onMouseClicked
    public void handleRectangleClick(MouseEvent event) {
        Rectangle r = (Rectangle) event.getTarget();
        String id = r.getId();
        if (event.getButton() == MouseButton.SECONDARY) {
            // wrong answer
            scores.put(id, scores.get(id) + QVALUE * -1);
        } else {
            // Good answer
            scores.put(id, scores.get(id) + QVALUE);
        }

        updateScores();
    }

    // Handler for Polygon[fx:id="nextQuestionButton"] onMouseClicked
    public void handleNextQuestion(MouseEvent event) {
        if (currentQuestion < question.size()-1) {
            currentQuestion++;
            displayQuestion();
        }
    }

    // Handler for Polygon[fx:id="prevQuestionButton"] onMouseClicked
    public void handlePrevQuestion(MouseEvent event) {
        if (currentQuestion > 0) {
            currentQuestion--;
            displayQuestion();
        }
    }

    // Handler for Button[fx:id="actionButton"] onAction
    public void handleActionButton(ActionEvent event) {
        // handle the event here
        String type = question.get(currentQuestion).type;
        FadeTransition fadeIn = new FadeTransition(Duration.millis(2000));
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        
        switch (type) {
            case "text":
                break;
            case "sound":
                player.play();
                break;
            case "video":
                fadeIn.setNode(mediaView);
                fadeIn.play();
                player.play();
                break;
            case "image":
                fadeIn.setNode(imageView);
                fadeIn.play();
                break;
        }
    }
    
    @Override // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
        
        currentQuestion = -1;
        questionArea.setText("");

        loadQuestions();
        initScores();
        updateScores();

        mediaView = new MediaView();
        mediaView.setFitHeight(640);
        mediaView.setFitWidth(480);
        
        imageView = new ImageView();
        imageView.setFitHeight(640);
        imageView.setFitWidth(480);

        mediaArea.getChildren().addAll(mediaView,imageView);
        
    }
    
    private void renderMedia(String type, String mediaUrl) {
        imageView.setVisible(false);
        mediaView.setVisible(false);
        if (player != null) {
            player.stop();
            mediaView.setMediaPlayer(null);
        }
        
        mediaUrl = MEDIAFOLDER.concat("/").concat(mediaUrl.replace("\\", "/"));
        
        switch (type) {
            case "text":
                break;
            case "sound":
                media = new Media(mediaUrl);
                player = new MediaPlayer(media);
                player.setAutoPlay(false);
                mediaView.setMediaPlayer(player);
                break;
            case "video":
                media = new Media(mediaUrl);
                mediaView.setVisible(true);
                mediaView.setOpacity(0);
                player = new MediaPlayer(media);
                player.setAutoPlay(false);
                mediaView.setMediaPlayer(player);
                break;
            case "image":
                image = new Image(mediaUrl);
                imageView.setVisible(true);
                imageView.setImage(image);
                imageView.setOpacity(0);
                break;
        }
    }

    private void initScores() {
        for (Integer i = 0; i < NBPLAYERS; i++) {
            scores.put("s" + i.toString(), 0);
        }
    }

    private void updateScores() {
        scoreLabel1.setText(scores.get("s0").toString());
        scoreLabel2.setText(scores.get("s1").toString());
    }

    @SuppressWarnings("CallToThreadDumpStack")
    private void loadQuestions() {

        try {
            Gson gson = new Gson();

            BufferedReader bufferedReader = new BufferedReader(new FileReader("questions.json"));
            question = gson.fromJson(bufferedReader, new TypeToken<List<Question>>() {}.getType());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void displayQuestion() {
        questionArea.setText(question.get(currentQuestion).question);
        renderMedia(question.get(currentQuestion).type,question.get(currentQuestion).media);
    }
}
